package puziran.sofa.json;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Json2ObjectUtilNew
{
  public static List<Map<String, Object>> fromJSONStr2List(String jsonStr)
    throws JSONException
  {
    JSONArray jsonArr = new JSONArray(jsonStr);
    List list = new ArrayList();
    for (int i = 0; i < jsonArr.length(); i++) {
      JSONObject json2 = jsonArr.getJSONObject(i);
      list.add(fromJSONStr2Map(json2.toString()));
    }
    return list;
  }

  public static Map<String, Object> fromJSONStr2Map(String jsonStr)
    throws JSONException
  {
    Map map = new HashMap();
    JSONObject json = new JSONObject(jsonStr);
    Iterator it = json.keys();
    while (it.hasNext()) {
      String key = (String)it.next();
      Object value = json.get(key);
      if ((value instanceof JSONArray)) {
        List list = new ArrayList();
        JSONArray jsonArr2 = (JSONArray)value;
        for (int i = 0; i < jsonArr2.length(); i++) {
          JSONObject json2 = jsonArr2.getJSONObject(i);
          list.add(fromJSONStr2Map(json2.toString()));
        }
        map.put(key.toString(), list);
      } else {
        map.put(key.toString(), value);
      }
    }
    return map;
  }

  public static void main(String[] args) throws Exception {
    List list = fromJSONStr2List("[{\"name\":\"Richard\",\"age\":7},{\"name\":\"Susan\",\"age\":4}]");
    System.out.println(((Map)list.get(0)).get("name"));
    Map map = fromJSONStr2Map("{\"name\":\"Richard\",\"age\":7}");
    System.out.println(map.get("name"));
  }
}